/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hva.web.mvcwebapp.classes;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

/**
 *
 * @author Thijs
 */
public class UploadClass {

    public UploadClass(){
        
    }
    public String doUpload(Part filePart, String folder_structure, HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            // get access to file that is uploaded from client
            InputStream is = filePart.getInputStream();
            // read filename which is sent as a part
            String filename = getFilename(filePart);    // read filename from stream
            // get filename to use on the server
            // For folder structure. Create folders for the specific structure
            String outputfile = session.getServletContext().getRealPath("images/"+folder_structure+"/"+filename);  // get path on the server
            System.out.println(outputfile);
            FileOutputStream os = new FileOutputStream(outputfile);

            // write bytes taken from uploaded file to target file
            int ch = is.read();
            while (ch != -1) {
                os.write(ch);
                ch = is.read();
            }
            os.close();
            return outputfile;
        } catch (Exception e) {
            out.println("Exception -->" + e.getMessage());
            return null;
        } finally {
            //out.close();
        }
        
    }

    private static String getFilename(Part part) {
        System.out.println(part.getHeader("content-disposition"));
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}
